<template>
  <div class="avatar-upload">
    <div class="avatar-preview" @click="triggerFileInput">
      <img :src="getAvatarUrl(modelValue)" class="avatar-img" :alt="alt" />
      <div class="upload-overlay">
        <el-icon><Plus /></el-icon>
        <span>点击上传</span>
      </div>
    </div>
    <input 
      ref="fileInput" 
      type="file" 
      accept="image/*" 
      class="file-input" 
      @change="handleFileChange" 
    />
    <div class="tips">支持 JPG、PNG 格式，大小不超过 20MB</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { authApi } from '@/api/auth'

interface Props {
  modelValue?: string
  size?: number
  alt?: string
}

const props = withDefaults(defineProps<Props>(), {
  size: 100,
  alt: '用户头像'
})

const emit = defineEmits<{(e: 'update:modelValue', value: string): void}>()

const fileInput = ref<HTMLInputElement | null>(null)

const triggerFileInput = () => {
  fileInput.value?.click()
}

const getAvatarUrl = (url?: string) => {
  if (!url) return new URL('../assets/default-avatar.svg', import.meta.url).href
  if (url.startsWith('http')) return url
  return `http://localhost:8080${url}`
}

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  try {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件')
      return
    }
    
    // 验证文件大小 (20MB)
    if (file.size > 20 * 1024 * 1024) {
      alert('文件大小不能超过 20MB')
      return
    }
    
    // 上传文件
    const response = await authApi.uploadAvatar(file)
    emit('update:modelValue', response.avatarUrl)
  } catch (error: any) {
    console.error('上传失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '网络错误'
    alert(`头像上传失败: ${errorMessage}`)
  } finally {
    // 清空文件输入框
    target.value = ''
  }
}
</script>

<style scoped>
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.avatar-preview {
  position: relative;
  cursor: pointer;
  transition: transform 0.2s;
}

.avatar-preview:hover {
  transform: scale(1.05);
}

.avatar-img {
  width: v-bind('props.size + "px"');
  height: v-bind('props.size + "px"');
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e4e7ed;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.2s;
}

.avatar-preview:hover .upload-overlay {
  opacity: 1;
}

.upload-overlay .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.file-input {
  display: none;
}

.tips {
  font-size: 12px;
  color: #909399;
}
</style>
